package com.qianfeng.zhangwei.xytg.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.qianfeng.zhangwei.xytg.R;
import com.qianfeng.zhangwei.xytg.adapter.GbCategoryAdapter;
import com.qianfeng.zhangwei.xytg.adapter.GbGoodAdapter;
import com.qianfeng.zhangwei.xytg.adapter.GbHotAdapter;
import com.qianfeng.zhangwei.xytg.adapter.HeadVpAdapter;
import com.qianfeng.zhangwei.xytg.bean.AppBean;
import com.qianfeng.zhangwei.xytg.bean.AppTop;
import com.qianfeng.zhangwei.xytg.bean.AppTopBean;
import com.qianfeng.zhangwei.xytg.bean.Category;
import com.qianfeng.zhangwei.xytg.bean.Good;
import com.qianfeng.zhangwei.xytg.constants.UrlConstants;
import com.qianfeng.zhangwei.xytg.utils.ImageLoaderHelper;
import com.qianfeng.zhangwei.xytg.utils.LocationHelper;
import com.qianfeng.zhangwei.xytg.widget.GridViewForViewGroup;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 */
public class GroupBuyFragment extends Fragment implements LocationHelper.BdLocationCallback, PullToRefreshBase.OnRefreshListener2<ListView> {
    /**
     * 商品信息相关
     */
    private PullToRefreshListView ptrListView;
    private GbGoodAdapter gbAdapter;
    private ArrayList<Good> goods = new ArrayList<>();
    private int page = 1;
    private AsyncHttpClient client;
    private HeadViewHolder vh;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        LocationHelper.getInstance().start();
//        LocationHelper.getInstance().setBdLocationCallback(this);
        client = new AsyncHttpClient();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_group_buy, container, false);
        initView(view, inflater);
        initHeadData();
        return view;
    }

    /**
     * 初始化UI
     *
     * @param view
     */
    private void initView(View view, LayoutInflater inflater) {
        vh = new HeadViewHolder(inflater);
        ptrListView = (PullToRefreshListView) view.findViewById(R.id.fragment_gb_ptrlistview);
        ptrListView.getRefreshableView().addHeaderView(vh.view);
        gbAdapter = new GbGoodAdapter(goods, getActivity());
        ptrListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, false));
        ptrListView.setOnRefreshListener(this);
        ptrListView.setAdapter(gbAdapter);
        ptrListView.setRefreshing();
    }


    private void initData() {
        /**
         * 获取商品信息
         */
        client.get(UrlConstants.getGoodsUrl(page), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (statusCode == 200) {
                    AppBean appBean = JSONObject.parseObject(responseString, AppBean.class);
                    if (appBean != null) {
                        if (page == 1 && !goods.isEmpty()) {
                            goods.clear();
                        }
                        goods.addAll(appBean.getResult().getData());
                        gbAdapter.notifyDataSetChanged();
                    }
                }
                ptrListView.onRefreshComplete();
            }
        });


    }

    private void initHeadData() {
        /**
         * 获取分类信息
         */
        client.get(UrlConstants.URL_GROUP_TYPE, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String response) {
                AppTopBean appTopBean = JSONObject.parseObject(response, AppTopBean.class);
                if (appTopBean != null && appTopBean.getStatus() == 1) {
                    for (int i = 0; i < 8; i++) {
                        vh.categories.add(appTopBean.getResult().get(i));
                    }
                    vh.categoryAdapter.notifyDataSetChanged();
                }
            }
        });

        /**
         * 获取热门推荐信息
         */
        client.get(UrlConstants.URL_GROUP_APPMID, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                AppTopBean bean = JSONObject.parseObject(responseString, AppTopBean.class);
                if (bean != null && bean.getStatus() == 1) {
                    vh.refreshAppTopView(bean.getData().getApptop());
                    vh.hots.addAll(bean.getData().getAdinfo());
                    vh.hotAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        page = 1;
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        page++;
        initData();
    }

    @Override
    public void locationCallback(double lat, double lngt) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationHelper.getInstance().stop();
    }

    private class HeadViewHolder implements AdapterView.OnItemClickListener {
        /**
         * 顶部广告栏相关
         */
        private ViewPager viewPager;
        private HeadVpAdapter headVpAdapter;
        private ArrayList<View> views = new ArrayList<>();

        /**
         * 分类控件相关
         */
        private GridViewForViewGroup categoryGridiView;
        private GbCategoryAdapter categoryAdapter;
        private ArrayList<Category> categories = new ArrayList<>();

        /**
         * 热门推荐
         */
        private GridViewForViewGroup hotGridView;

        private GbHotAdapter hotAdapter;
        private ArrayList<AppTop> hots = new ArrayList<>();

        private View view;

        public HeadViewHolder(LayoutInflater inflater) {
            this.view = inflater.inflate(R.layout.gb_head_layout, ptrListView, false);

            /**
             * 添加头部viewpager控件
             */
            viewPager = (ViewPager) view.findViewById(R.id.gb_head_viewpager);
            headVpAdapter = new HeadVpAdapter(views);
            viewPager.setAdapter(headVpAdapter);
            /**
             * 添加分类gridview
             */
            categoryGridiView = (GridViewForViewGroup) view.findViewById(R.id.gb_head_category_gridview);
            categoryAdapter = new GbCategoryAdapter(categories, getActivity());
            categoryGridiView.setAdapter(categoryAdapter);
            categoryGridiView.setOnItemClickListener(this);
            /**
             * 添加热门推荐
             */
            hotGridView = (GridViewForViewGroup) view.findViewById(R.id.gb_head_hot_gridview);
            hotAdapter = new GbHotAdapter(hots, getActivity());
            hotGridView.setAdapter(hotAdapter);
        }

        /**
         * 刷新广告栏数据
         *
         * @param list
         */
        private void refreshAppTopView(List<AppTop> list) {
            DisplayImageOptions options = ImageLoaderHelper.getInstance().getDisplayImageOptions(R.mipmap.list_default, R.mipmap.list_default);
            if (list != null && !list.isEmpty()) {
                for (AppTop appTop : list) {
                    ImageView imageView = new ImageView(getActivity());
                    imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    String imageUrl = UrlConstants.URL_IMAGE + appTop.getImage();
                    ImageLoader.getInstance().displayImage(imageUrl, imageView, options);
                    views.add(imageView);
                }
            }
            headVpAdapter.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    }


}
